/** @odoo-module **/
import init_grid_options from '../ag_grid/gridOptions.js'
import {toObj,add_material_item_bom_unit_ratio_id,formatId,arryIsRepeat,keepTwoDecimal} from "../ag_grid/tool.js";
import selectCellEditor from "../ag_grid/selectCellEditor.js";
import numberCellEditor from "../ag_grid/numberCellEditor.js";

const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent
} = owl;

class UnitRatioModal extends Component {
    static template = xml`
    <div class="modal-backdrop fade show unitRatioModalBackdrop" t-if="props.is_open" style="z-index:1055;opacity: 0.2;"></div>
        <!--单位转化 -->
        <div class="modal fade " id="unitRatioModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5">
                            <t t-esc="state.headTitle"/>
                        </h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row justify-content-end mb-3">
                            <div class="col-auto">
                                <button type="button" class="btn btn-outline-primary btn-xs" t-on-click.stop="handleAddRow">添加</button>
                            </div>
                        </div>
                        <div t-ref="unitRatioGrid" style="width: 100%;height:300px" class="ag-theme-balham myGrid"/>
                    </div>
                    <div class="modal-footer">
                        <div class="text-danger" style="flex:1">
                            <t t-esc="state.msg"/>
                        </div>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" t-on-click.stop="handleSubmitModel">确定</button>
                    </div>
                </div>
            </div>
        </div>      
    `;
    static props = {
        is_open: {type: Boolean,optional:true},
        data: {type: Object,optional:true}
    };

    setup() {
        this.state = useState({
            headTitle: '单位转化',
            form: {},
            msg: '',
            isCheck:true
        });
        this.unitRatioGrid_ref = useRef('unitRatioGrid');
        this.material_purchase_unit_category = {};
        this.material_item = {};
        this.index = {};
        this.rowData = [];

        onMounted(() => {
            let _this = this;
            this.unitRatioModal = new bootstrap.Modal('#unitRatioModal', {
                toggle:'modal'
            });

            document.getElementById('unitRatioModal').addEventListener('hidden.bs.modal', event => {
                _this.state.form = {};
                _this.env.closeUnitRatioModal();
            })

            this.gridOptions = Object.assign({}, init_grid_options(), {
                rowData: [],
                suppressRowClickSelection: false,
                columnDefs: [
                    {
                        headerName: '',
                        field: 'check',
                        menuTabs: [],
                        width: 50,
                        editable: false,
                        checkboxSelection: true, //设置为true显示为复选框
                    },

                    {
                        headerName: '单位',
                        field: 'unit_id',
                        menuTabs: [],
                        flex: 1,
                        cellEditor:selectCellEditor,
                        cellEditorParams:(params) => {
                            let material_main_unit_id = params.context.owl_widget.material_main_unit_id;
                            let material_purchase_unit_id = params.context.owl_widget.material_purchase_unit_id;
                            let unit_arr = params.context.owl_widget.index.material_purchase_unit_category.filter(v=>v.id != material_main_unit_id && v.id != material_purchase_unit_id);
                            return {
                                values: unit_arr
                            };
                        },
                        type: 'editableColumn',
                        valueFormatter:(params)=>{
                            if(params.value!= ''){
                                return '1'+params.context.owl_widget.material_purchase_unit_category[params.value].name
                            }else{
                                return ''
                            }
                        },
                        cellClassRules:{
                            'bg_gray':(params)=>!_this.isCellEditable(params)
                        }
                    },
                    {
                        headerName: '=',
                        field: 'test',
                        menuTabs: [],
                        width: 50,
                        editable:false,
                        valueFormatter:(params)=>{
                            return '='
                        },
                        cellClassRules:{
                            'bg_gray':(params)=>true
                        }
                    },
                    {
                        headerName: '比例',
                        field: 'jin_ratio',
                        menuTabs: [],
                        flex: 1,
                        cellEditor:numberCellEditor,
                        cellEditorParams:(params) => {
                            return {
                                values: {
                                    decimal:true,
                                    toFixed:2
                                },
                            };
                        },
                        type: 'editableColumn',
                        cellClassRules:{
                            'bg_gray':(params)=>!_this.isCellEditable(params)
                        }
                    },
                    {
                        headerName: '斤',
                        field: 'main_unit_id',
                        menuTabs: [],
                        flex: 1,
                        editable:false,
                        valueGetter:(params)=>{
                            let main_unit_id = params.context.owl_widget.main_unit_id;
                            return params.context.owl_widget.material_purchase_unit_category[main_unit_id].name
                        },
                        cellClassRules:{
                            'bg_gray':(params)=>true
                        }
                    },
                ],
                context: {
                    owl_widget: _this
                },
                onSelectionChanged: () => {
                    // const selRows = _this.gridOptions.api.getSelectedRows();
                    // if (selRows.length == 0) {
                    //     _this.state.msg = '请勾选单位';
                    // } else {
                    //     _this.state.msg = '';
                    // }
                    _this.checkForm();
                },
                onCellValueChanged: (e) => {
                    // console.log(e);
                    _this.onCellValueChanged(e);
                },
                columnTypes:{
                    editableColumn:{
                        editable: (params) => {
                            return _this.isCellEditable(params);
                        },
                    }
                },
                getContextMenuItems: (e) => {
                    return _this.setAGMenus(e);
                },
                stopEditingWhenCellsLoseFocus:true
            });

            this.unitRatioGrid = new agGrid.Grid(this.unitRatioGrid_ref.el, this.gridOptions);
        })

        onWillUpdateProps(nextProps => {
            // console.log(nextProps);
            if (nextProps.is_open) {
                return this.openModel(nextProps.data);
            }
        });

        this.handleAddRow = _.debounce(this.addRow,300);
        this.handleSubmitModel = _.debounce(this.submitModel,300);
    }
    onCellValueChanged(params){
        let data = params.data;
        let colId = params.colDef.field;
        if(colId == 'unit_id'){
            let radio = this.env.getWeightRatio(this.main_unit_id, params.newValue);
            if(radio!=0){
                params.node.setDataValue('jin_ratio',radio)
            }
        }
        if(params.newValue && colId == 'jin_ratio'){
            params.node.setDataValue('jin_ratio',Number(params.newValue)||0)
        }
        this.checkForm();
    }
    isCellEditable(params){
        let flag = false;
        let data = params.data;
        let colId = params.colDef.field;
        if(data.unit_id == this.material_main_unit_id && colId == 'unit_id'){
            return false;
        }
        if(data.unit_id == this.material_purchase_unit_id && colId == 'unit_id'){
            return false;
        }
        if((data.id+'').startsWith('virtual_')){
            flag = true;
        }else if(colId == 'jin_ratio'){
            flag = true;
        }
        if(flag && colId == 'jin_ratio') {
            let radio = this.env.getWeightRatio(this.main_unit_id, data.unit_id);
            radio != 0 && (flag = false)
        }
        return flag;
    }

    openModel(data) {
        let index = this.env.getIndex();
        this.index = index;
        this.material_item = toObj(index.material_item,'id');
        this.material_purchase_unit_category = toObj(index.material_purchase_unit_category,'id');
        this.main_unit_id = 9;
        this.rowData = index.material_item_unit_ratio.filter(v=>v.material_id+'' == data.material_id+'');
        this.material_main_unit_id = this.material_item[data.material_id].main_unit_id;
        this.material_purchase_unit_id = this.material_item[data.material_id].purchase_unit_id;
        // console.log(data.material_id);
        let newUnitId = data.unit_id || '';
        if(data.keyword){
            let unit = this.index.material_purchase_unit_category.find(v => v.name == data.keyword);
            let isHad = this.rowData.find(v=>v.unit_id == unit.id);
            unit && !isHad && (newUnitId = unit.id)
        }
        if(newUnitId){
            let radio = this.env.getWeightRatio(this.main_unit_id, newUnitId);
            this.rowData.unshift({
                id:add_material_item_bom_unit_ratio_id(),
                material_id:data.material_id,
                unit_id:newUnitId,
                jin_ratio:radio!=0?radio:''
            })
        }
        // let purchase_unit_id = this.material_item[data.material_id].purchase_unit_id;
        // if(purchase_unit_id){
        //     let item = this.rowData.find(v=>v.unit_id == purchase_unit_id);
        //     if(!item){
        //         this.rowData.unshift({
        //             id:add_material_item_bom_unit_ratio_id(),
        //             // main_unit_bom_unit_ratio:radio!=0?radio:'',
        //             material_id:data.material_id,
        //             // purchase_unit_id:newUnitId,
        //             unit_id:purchase_unit_id,
        //             unit_ratio:1
        //         })
        //     }
        // }

        if(data.action == 'edit'){
            this.state.isCheck = false;
        }else{
            this.state.isCheck = true;
        }
        this.gridOptions.api.setRowData(this.rowData);
        let headTitle = '【单位转化】'+this.material_item[data.material_id].name;
        this.state.headTitle = headTitle;
        this.unitRatioModal.show();
        // this.unitRatioModal.toggle();
    }

    // 提交
    async submitModel() {
        let rowData = this.getRowData();
        this.checkForm();
        if (this.state.msg != '') {
            return;
        }
        let data = rowData.map(v=>{
            return {
                id: formatId(v.id),
                material_id: formatId(v.material_id),
                unit_id: formatId(v.unit_id),
                jin_ratio: Number(v.jin_ratio)
            }
        });

        let res = await this.env.updateMaterialItemBomUnitRatio(formatId(this.props.data.material_id),data);

        // res.forEach((id, index) => {
        //     Object.assign(rowData[index], {
        //         id
        //     })
        // })

        if(typeof (this.props.data.callback) == 'function'){
            if(this.state.isCheck){
                const selRows = this.gridOptions.api.getSelectedRows();
                let unit_id = formatId(selRows[0].unit_id);
                let unit_name = this.material_purchase_unit_category[unit_id].name;
                this.props.data.callback({unit_id,unit_name});
            }else{
                this.props.data.callback();
            }
        }

        this.unitRatioModal.hide();
    }

    checkForm(){
        const selRows = this.gridOptions.api.getSelectedRows();
        if (this.state.isCheck && selRows.length == 0) {
            this.state.msg = '请勾选单位';
            return;
        }
        let rowData = this.getRowData();
        let flag = false;
        rowData.forEach(v=>{
            if(!v.jin_ratio){
                this.state.msg = "请填写比例";
                flag = true;
            }
            if(!v.unit_id){
                this.state.msg = "请选择'单位'";
                flag = true;
            }
        });
        if(flag){
            return;
        }
        let purchase_unit_ids = rowData.map(v=>v.unit_id);
        if(arryIsRepeat(purchase_unit_ids)){
            this.state.msg = "'单位'不能重复";
            return;
        }

        this.state.msg = '';
    }

    addRow(){
        let data = {
            id:add_material_item_bom_unit_ratio_id(),
            jin_ratio:'',
            material_id:this.props.data.material_id,
            unit_id:''
        };
        this.gridOptions.api.applyTransactionAsync({ add: [data] },(res) => {
            // this.gridOptions.api.redrawRows();
        });
    }

    removeRow(data){
        this.gridOptions.api.applyTransactionAsync({ remove: [data] },(res) => {
            // this.gridOptions.api.redrawRows();
            // this.refreshCells();
            this.checkForm();
        });
    }

    setAGMenus(e){
        let node = e.node || {};
        // console.log(node.rowIndex);
        if (!node.data) {
            return;
        }
        if(!e.column){
            return;
        }
        let _this = this;
        let data = node.data;
        let menus = [];
        let material_id = this.props.data.material_id;
        if(this.material_main_unit_id == data.unit_id){
            return menus;
        }
        if(this.material_purchase_unit_id == data.unit_id){
            return menus;
        }
        if((data.id+'').startsWith('virtual_')){
            menus.push({
                name: '删除本行',
                action: () => {
                    _this.removeRow(node.data);
                },
                cssClasses: ['text-danger'],
            })
        }


        return menus;
    }

    getRowData(id){
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode(function (node) {
            if(node.data){
                if(id){
                    node.data.id == id && (rowData.push(node.data));
                }else{
                    rowData.push(node.data);
                }
            }
        });
        // console.log(rowData);
        return rowData;
    }
}


export {
    UnitRatioModal
}
